// const env = require('./config.js'); //配置文件，在这文件里配置你的OSS keyId和KeySecret,timeout:87600;
import OSSConfig from './config.js';

var env = null;
let forFun = async () => {
	let res = await new OSSConfig().getConfig();
	if (res) {
		env = res;
	} else {
		setTimeout(() => {
			forFun
		}, 300);
	}
}
forFun();
import cryptojs from './crypto.js';
import base64 from './base64.js';
export default {
	/*
	 *上传文件到阿里云oss 
	 *@param - filePath :图片的本地资源路径
	 *@param - dir:表示要传到哪个目录下
	 *@param - successc:成功回调
	 *@param - failc:失败回调
	 */
	async uploadFile({
		filePath,
		fileName,
		successc,
		failc
	}) {
		if (!filePath) {
			failc({
				title: '图片错误',
				content: '请重试',
				showCancel: false,
			})
			return;
		}
		//图片名字 可以自行定义，     这里是采用当前的时间戳 + 150内的随机数来给图片命名的
		const aliyunFileKey = fileName;
		let aliyunServerURL = env.uploadImageUrl; //OSS地址，需要https;

		const accessid = env.OSSAccessKeyId;
		const policyBase64 = this.getPolicyBase64();
		const signature = this.getSignature(policyBase64); //获取签名    
		await wx.uploadFile({
			url: env.uploadImageUrl, //开发者服务器 url
			filePath: filePath, //要上传文件资源的路径
			name: 'file', //必须填file
			formData: {
				'key': aliyunFileKey,
				'policy': policyBase64,
				'OSSAccessKeyId': accessid,
				'signature': signature,
				'x-oss-security-token': env.securityToken, // 使用STS签名时必传。 
				'success_action_status': '200',
			},
			success: function (res) {
				console.log('上传返回信息', res);
				if (res.statusCode != 200) {
					failc(new Error('上传错误:' + JSON.stringify(res)))
					return;
				}
				successc(aliyunServerURL + aliyunFileKey);
			},
			fail: function (err) {
				console.log('上传返回失败信息', err);
				// err.wxaddinfo = aliyunServerURL;
				failc(err);
			},
		})
	},
	getPolicyBase64() {
		let date = new Date();
		date.setHours(date.getHours() + env.timeout);
		let srcT = new Date(date).toISOString();
		const policyText = {
			"expiration": srcT, //设置该Policy的失效时间，超过这个失效时间之后，就没有办法通过这个policy上传文件了 
			"conditions": [
				["content-length-range", 0, 5 * 1024 * 1024] // 设置上传文件的大小限制,5mb
			]
		};
		const policyBase64 = base64.encode(JSON.stringify(policyText));
		return policyBase64;
	},
	getSignature(policyBase64) {
		const accesskey = env.AccessKeySecret;
		const bytes = cryptojs.HMAC(cryptojs.SHA1, policyBase64, accesskey, {
			asBytes: true
		});
		const signature = cryptojs.util.bytesToBase64(bytes);
		console.log(signature);
		return signature;
	}
};